﻿/**
* 提供对LoadBox的控制
*
* @Experience
 * 当同时有多个LoadBox时,通过LoadManager对所有的LoadBox进行控制先后加载(顺序加载).
 * 
 * 1、当uid已经存在时,
*/

package org.nickro.utils{
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	
	import org.nickro.controls.LoadBox;
	import org.nickro.events.LoadEvent;
	
	public class LoadManager extends EventDispatcher
	{
		private static var _instance:LoadManager
		private static var _allowInstance:Boolean = false;
		
		private var loaderDict:Dictionary = new Dictionary(true);
		private var loaders:Array = [];
		private var loadingIndex:int = 0;
		private var isLoading:Boolean = false;
		public function LoadManager()
		{
			if(!LoadManager._allowInstance)
			{
				throw new Error("Error: Use LoadManager.getInstance() instead of the new keyword.");
			}
		}
		
		public static function getInstance():LoadManager
		{
			if(LoadManager._instance == null)
			{
				_allowInstance = true;
				_instance = new LoadManager();
				_allowInstance = false;
			}
			return _instance;
		}
		
		public function addLoadBox(loader:LoadBox,uid:String):Boolean
		{
			//uid与url是对应的，所以不需进行唯一检测，因为url是唯一的
			/* for(var i:int = 0;i < loaders.length ; i++)
			{
				if(uid == loaders[i].uid)
				{
					return loaderDict[uid].target;
					return false;
					throw new Error(uid + "has been used!plz change another uid.")
				}
			} */
			var obj:Object = {};
			obj.uid = uid;
			obj.target = loader;
			//obj.loadIndex = loadingIndex;
			loaders.push(obj);
			//loaderDict[uid] = obj;
			loopLoad();
			trace(loaders.length);
			return true;
		}
		
		private function loopLoad():void
		{
			loaders[loadingIndex].target.start();
			loaders[loadingIndex].target.addEventListener(LoadEvent.COMPLETE,onLineComplete);			
		}
		
		private function onLineComplete(e:LoadEvent):void
		{
			e.currentTarget.removeEventListener(LoadEvent.COMPLETE,onLineComplete);	
			//发送LoadEvent.COMPLETE事件
			e.currentTarget.dispatchEvent(new LoadEvent(LoadEvent.COMPLETE,e.data));		
			if(loadingIndex + 1 == loaders.length)
			{
				restore();
			}else
			{
				loadingIndex++;
				loopLoad();
			}
		}
		/**
		 * 当全部加载完成后,还原LoadManager初始化状态
		 * 
		 */
		public function restore():void
		{
			destroy();
			loadingIndex = 0;
		}
		
		private function destroy():void
		{
			var l:int = loaders.length
			for(var i:int = 0;i < l ; i++)
			{
				loaders.pop();
			}
		}
	}
}